
<template>
    <div class="manage-cate" v-loading="loading">
      <div class="manage-btn" v-if="courseDetail.id">
          <div class="name" :style="{visibility: courseDetail.id ? 'visible' : 'hidden'}">
            <Ellipsis :content="courseDetail.title"/>
          </div>
          <div v-if="courseDetail.id">
            <el-button class="srt-el-button srt-el-button-h32 btn" type="primary" @click="handleUpdate">移除</el-button>
            <el-button class="srt-el-button srt-el-button--primary srt-el-button-h32 btn" type="primary" @click="handleEdit">编辑</el-button>
          </div>
      </div>
      <template v-if="folderData.length">
            <div class="manage-title">
                <span class="time">课程时长：<span class="blue">{{ fmtTransTime(moocTimes)}}</span></span>
                <span class="state">
                    <el-popover
                        ref="popoverRef"
                        trigger="hover"
                        :width="200"
                    >
                        <template #reference>
                            <i class="iconfont icon-shuoming icon"></i>
                        </template>
                        <div>
                           <p>开放：该章节对所有学员可见，可学习；</p>   
                           <p>隐藏：该章节学员不可见，且学员已产生的学习数据将不计算成绩</p>   
                        </div>
                    </el-popover>开放状态
                </span>
            </div>
            <el-tree ref="folderTreeRef" :data="folderData" node-key="catalogueId"
                :expand-on-click-node="true" :auto-expand-parent="true"
                :default-expand-all="false"
                @node-click="checkClick"
                :render-after-expand="false" :icon="ArrowRight" class="folder-tree" 
                :indent="20" :props="defaultProps" empty-text="暂无课程目录">
                <template #default="{ data }">
                    <div :class="['catalogue-tag', fmtCatalogue(data.tag, data.catalogueType)]" >
                        <span class="title">
                            <span class="title-name">
                                <ellipsis :content="data.catalogueName"/>
                            </span>
                            <!-- <span class="show-subtitle" v-if="handleSubTitle(data)">字幕</span> -->
                        </span>
                        <div @click.stop class="manage-op">
                            <span v-if="data.catalogueType === 0" class="op">
                                <el-switch
                                    class="open-switch"
                                    v-model="cateHideStateMap[data.catalogueId]"
                                    @change="handleSet(data)"
                                    :disabled="cateHideMap[data.catalogueId] && !cateHideMap[data.catalogueId].id"
                                    style="--el-switch-on-color: #BFBFBF; --el-switch-off-color: #24B676"
                                />
                                <span class="label">{{ cateHideStateMap[data.catalogueId] ?  '隐藏' : '开放'}}</span>
                                <!-- <span class="manage-tag" v-if="!cateHideMap[data.catalogueId]">
                                    <i class="iconfont icon-dui1 show"></i>开放</span>
                                <span class="manage-tag" v-else><i class="iconfont icon-bukejian"></i>隐藏</span> -->
                                <!-- <el-button :disabled="cateHideMap[data.catalogueId] && !cateHideMap[data.catalogueId].id" class="srt-el-button srt-el-button--link srt-el-button-h28" @click="handleSet(data)">设置</el-button> -->
                            </span>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28" v-else-if="data.tag !== 'comment'"  @click="handlePreview(data)">预览</el-button>
                        </div>
                    </div>
                </template>
            </el-tree>
        </template>
        <div v-else-if="courseDetail.id">
            <NoData url="no-course.png" :show-info="false">
                <div class="no-data-info">
                    暂无内容<el-button class="srt-el-button srt-el-button--link btn" @click="handleEdit">点击添加</el-button>
                </div>
            </NoData>
        </div>
        <div v-else>
            <NoData url="no-course.png" info="暂无课程章节"></NoData>
            <div class="add-course-btns">
                <el-button class="srt-el-button srt-el-button--primary srt-el-button-h32 new-add" @click="handleAdd">+添加课程章节</el-button>
                <el-button class="srt-el-button srt-el-button-h32" @click="handleUpdate">选择已有课程章节</el-button>
            </div>
        </div>
    </div>
    <!-- <SettingDialog v-model="showDialog" :form="catalogueData" @refresh-list="refreshList"/> -->
    <ListDrawer v-model="showListDialog" @confirm="confirmCheck" @handle-add="handleAdd"/>
    <ContentPreviewDialog v-model="previewsDialog" :form="catalogueData"/>
</template>

<script setup>
import NoData from '@/components/no-data.vue';
import SettingDialog from './dialog/setting-dialog.vue';
// import ListDialog from './dialog/list-dialog.vue';
import ListDrawer from './dialog/list-drawer.vue';
import ContentPreviewDialog from '@/components/content-preview-dialog.vue';
import { ref, onMounted, watch, nextTick} from 'vue';
import { ArrowRight } from '@element-plus/icons-vue';
import Confirm from '@/components/confirm/confirm.js'
import { useRoute } from 'vue-router';
import { fmtTransTime } from '@/lib/biz-tools.js'
import Ellipsis from '@/components/ellipsis.vue';
import { queryToJson, treeForEach } from '@/lib/tools';

const emit = defineEmits(['update-detail']);

const route = useRoute();


const props = defineProps({
    detail: {
        type: Object,
        default: () => {
            return {};
        }
    }
})

// 课程内容
const courseDetail = ref({});

// 是否显示对话框
const showDialog = ref(false);

// 目录内容
const catalogueData = ref({});

const folderData = ref([]);

// 目录视频对应的字幕数组
const subTitleMap = ref({});

const folderTreeRef = ref(null);

const loading = ref(false);

const catalogueMap = ref({});

// 选择课程素材
const showListDialog = ref(false);

const moocTimes = ref('');

const cateHideMap = ref({});

const cateHideStateMap = ref({});

const previewsDialog = ref(false);

watch(() => props.detail, async (val) => {
    if(val.id) {
        courseDetail.value = val?.courseList?.length && val.courseList[0] || {};
        await getList();
        refreshList();
    }
}, {immediate: true})

const defaultProps = {
    isLeaf: 'isLeaf',
    children: 'children',
    label: 'catalogueName',
    class: customNodeClass
}


// 设置开放隐藏
function handleSet(data) {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    let catalogueData = {catalogueId: data.catalogueId, courseId: courseDetail.value.id, id: cateHideMap.value[data.catalogueId]?.id};
    confirmSet(catalogueData);
}

// 确定设置
function confirmSet (catalogueData) {
    let params1 = {
        queries: {
            id: catalogueData.id
        }
    }
    let params2 = {
        data: {
            bizId: route.params.moocId,
            bizScene: 'mooc',
            contentType: 'catalogue',
            courseId: catalogueData.courseId,
            contentId: catalogueData.catalogueId
        }
    }
    let params = catalogueData.id ? params1 : params2;
    let portalName = catalogueData.id ? 'moocCourseSetDelete' : 'moocCourseSetCreate';

    G_transmit(portalName, {
    ...params,
    }).then((res) => {
        G_dispatchEvent('toast', { message: '设置成功', type: 'success' });
    }).catch((_err) => {
        console.log(_err)
    }).finally(() => {
        refreshList();
    })
}


function customNodeClass(data, node) {
    if (data.pid == 0) {
        return 'catalogue-parent'
    }
    if(data.catalogueType === 1) {
        return 'catalogue-leaf'
    }
    return ''
}

function fmtCatalogue(tag, type) {
    if(type === 0) {
        return '';
    }
    let arr = tag && tag.split(',') || [];
    return arr.length && arr[0];
};


function getList() {
    // 没有课程id
    if(!courseDetail.value.id) {
        return;
    }
    loading.value = true;
    return G_transmit('getFolderTree', {
        queries: {
            courseId: courseDetail.value.id,
            pathDeep: 5,
            showData: true,
            queryAll: true
        }
    }).then((res) => {
        folderData.value = res.data || [];
        catalogueMap.value = refreshCatalogue(folderData.value);
        nextTick(() => {
            getSubTitleList();
        })
    }).catch((_err) => {
        console.log(_err)
    }).finally(() => {
        loading.value = false;
    })
}



// 添加/删除课程素材
function handleUpdate() {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }

    if(courseDetail.value.id) {
        Confirm(
            { 
                title: '确认移除章节吗？', 
                text: '所有目录将会被移除，可再次添加，确认移除吗？'
            }
        )
        .then(ret => {
            confirmDelete();
        })
        .catch(_err => {
            console.log(_err);
        }) 
    }else {
        showListDialog.value = true;
    }
}

// 新建课程章节
function handleAdd () {
        if (!props.detail.id) {
            G_dispatchEvent('toast', { message: '请先完善慕课', type: 'error' })
            return;
        }
        let params = {
            title: props.detail.title,
            lecturerList: props.detail.lecturerList || [],
            bizSourceId: 0,
            templateId: 0,
            bizSource: 'mooc',
            type: 'mooc',
            state: 0, // 状态（0-暂存、1-提交（待提审）
            publishState: 1, // 发布状态（0-未发布 1-已发布）
        }
        if (props.detail.stageSubjectList && props.detail.stageSubjectList.length) {
            params.stageSubjectList = props.detail.stageSubjectList;
        }
        if (props.detail.gradeList && props.detail.gradeList.length) {
            params.gradeList = props.detail.gradeList;
        }
        G_transmit('courseCreate', {
            data: params
        })
            .then((res) => {
                let courseId = res.data;
                let tabStr = queryToJson().tabStr;
                G_go({
                    name: 'addDesign',
                    params: {
                        courseId: courseId
                    },
                    query: {
                        step: 2,
                        tabStr,
                        type: 1, // 隐藏step
                        moocId: props.detail.id
                    }
                })
                // if(hideStep.value) {
                //     back();
                //     return;
                // }
                // emit('change-step', 2);
                // let courseId = res.data || queryToJson().courseId;
                // let tabStr = queryToJson().tabStr;
                // if(courseId) {
                //     window.history.pushState('', '', `?courseId=${courseId}&step=2&tabStr=${tabStr || ''}`);
                // }else {
                //     window.history.pushState('', '', `?step=2&tabStr=${tabStr || ''}`)
                // }
            })
            .catch((err) => {
                console.log(err)
            }).finally(() => {
                loading.value = false;
            });
}

// 编辑课程章节
function handleEdit () {
    if (!(props.detail.state === 1 || props.detail.state === 3)) {
        let message = props.detail.publishState === 1 && props.detail.state === 4 ? '该慕课已发布，请取消发布后再操作' : '该慕课正在审核中，无法操作';
        G_dispatchEvent('toast', { message, type: 'error' })
        return;
    }
    let tabStr = queryToJson().tabStr || '';
    G_go({
        name: 'editDesign',
        params: {
            courseId: courseDetail.value.id
        },
        query: {
            step: 2,
            type: 1, // 隐藏step
            tabStr,
            moocId: props.detail.id
        }
    })
}
function confirmDelete() {
    G_transmit('moocContentDelete', {
        data: {
            moocId: route.params.moocId,
            contentType: 'course',
            contentId: courseDetail.value.id
        }
    }).then((res) => {
        G_dispatchEvent('toast', { message: '移除成功', type: 'success' });
        courseDetail.value = {};
        folderData.value = [];
        emit('update-detail');
    }).catch((_err) => {
        console.log(_err)
    }) 
}

// 添加课程素材
function confirmCheck(courseVal) {
    G_transmit('moocContentSave', {
        data: {
            moocId: route.params.moocId,
            contentType: 'course',
            contentId: courseVal.id
        }
    }).then((res) => {
        G_dispatchEvent('toast', { message: '添加成功', type: 'success' });
        courseDetail.value.id = courseVal.id;
        cateHideMap.value = {};
        cateHideStateMap.value = {};
        emit('update-detail');
    }).catch((_err) => {
        console.log(_err)
    })
}


// 获取慕课时长
function getMoocDuration() {
    G_transmit('moocDuration', {
        queries: {
            moocId: route.params.moocId,
        },
        silence:true
    }).then((res) => {
        moocTimes.value = res.data;
    }).catch((_err) => {
        console.log(_err)
    })
}



/**
 * 获取隐藏目录列表
 */
function getMoocHideList() {
     // 没有课程id
    if(!courseDetail.value.id) {
        return;
    }
    cateHideMap.value = {};
    let hideStateMap = {};
    G_transmit('moocCourseSetList', {
        data: {
            bizId: route.params.moocId,
            bizScene: 'mooc',
            contentType: 'catalogue',
            courseId: courseDetail.value.id
        },
        silence: true, // 默认不提示消息
    }).then((res) => {
        let list = res.data || [];
        list.forEach(item => {
            cateHideMap.value[item.contentId] = item;
            hideStateMap[item.contentId] = true;
            catalogueMap.value && Object.keys(catalogueMap.value).forEach(subKey => {
                if(catalogueMap.value[subKey] && catalogueMap.value[subKey].includes(item.contentId)){
                    cateHideMap.value[subKey] = {contentId: catalogueMap.value[subKey]};
                    hideStateMap[subKey] = true;
                }
            })
        })
        cateHideStateMap.value = hideStateMap;
    }).catch((_err) => {
        console.log(_err)
    })
}

// 遍历所有目录, 设置所有子目录节点的 父节点
function refreshCatalogue(catalogueList, catalogueMap = {}, rootId = '0', parentIdList = []) {
    if(catalogueList.length) {
        catalogueList.forEach(item => {
            let pList = [...parentIdList, rootId]
            if(rootId !== '0') {
                catalogueMap[item.catalogueId] = pList; 
            }
            if(item.children && item.children.length && item.children[0].catalogueType === 0) {
                refreshCatalogue(item.children, catalogueMap, item.catalogueId, pList);
            }
        })
    }
    return catalogueMap;
}




function refreshList() {
    getMoocHideList();
    getMoocDuration();
}


function handlePreview(data) {
    catalogueData.value.title = data?.catalogueName;
    catalogueData.value.materialVO = data?.courseWare?.materialVO;
    previewsDialog.value = true;
}

// 预览
function checkClick(data) {
    if(data.catalogueType === 1 && data.tag !== 'comment') { // 目录类型{0.文件目录1课件}
        handlePreview(data);
    }
}

// 获取字幕列表 目录有视频获取字幕
function getSubTitleList () {
    let videoIds = [];
    if (folderData.value && folderData.value.length) {
        treeForEach(folderData.value, item => {
            if (item.catalogueType === 1 && item.courseWare && item.courseWare.contentId && item.tag === 'video') {
                videoIds.push(item.courseWare.contentId);
            }
        })
    }
    if (videoIds.length > 0) {
        G_transmit('subtitleSearch', {
            data: {
                materialIds: videoIds,
                subtitleInitType: 1
            }
        }).then(async (res) => {
            subTitleMap.value = {};
            (res.data || []).forEach(item => {
                subTitleMap.value[item.materialId] = item;
            })
        }).catch((_err) => {
            console.log(_err)
        }).finally(() => {
        })
    }
}

// 控制是否显示字幕
function handleSubTitle (data) {
    if (data.catalogueType === 1 && data.tag=== 'video' && data.courseWare.contentId && subTitleMap.value[data.courseWare.contentId]) {
        return true;
    } else {
        return false
    }
}


onMounted(() => {
    // getMoocDuration();
})


</script>

<style lang="scss" scoped>

@mixin img-style(){
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
    vertical-align: middle;
    margin-right: 8px;
    margin-left: 7px;
}

.folder-tree {
    margin-top: 20px;
    :deep(.el-tree-node) {
        font-size: 14px;
    }
    :deep(.catalogue-leaf) {
        .el-tree-node__expand-icon {
            display: none;
        }
        .el-tree-node__content {
            color: var(--main-text-color);
            // border: none;
        }
    }
    :deep(.catalogue-border) {
        .el-tree-node__content {
            border: none;
        }
    }
    :deep(.el-tree-node__expand-icon:not(.is-leaf)) {
        color: var(--main-text-color);
    }

    :deep(.el-tree-node__content) {
        height: 50px;
        color: var(--main-text-color);
        border-bottom: 1px solid #E0E2E4;
        &:hover {
            background: #E7F1FF;
            border-radius: 4px;
        }
    }
    :deep(.el-tree-node__expand-icon) {
        margin-left: 4px;
    }

    :deep(.el-tree-node:focus) {
        &.catalogue-parent>.el-tree-node__content {
            background-color: #F7F9FA;
        }
        &>.el-tree-node__content {
            background-color: transparent;
        }
    }
}

:deep(.catalogue-parent) {
    padding-bottom: 20px;
    & > .el-tree-node__content {
        height: 50px;
        background: #F7F9FA;
        border-radius: 4px;
        font-weight: bold;
        color: var(--main-text-color);
        border: none;
    }
}

:deep(.active) {
    & > .el-tree-node__content {
        background: #E7F1FF;
    } 
}
.catalogue-tag {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 20px;
    .title {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex: 1;
        overflow: hidden;
        .title-name {
            display: inline-block;
            max-width: calc(100% - 200px);
            // flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .show-subtitle {
            color: #47698C;
            margin-left: 4px;
            padding: 0 4px;
            background: #EFF0F2;
            border-radius: 4px;
            line-height: 20px;
        }
    }
    &.doc, &.docx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/doc.png') no-repeat;
            background-size: contain;
        }
    }
    &.ppt, &.pptx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/ppt.png') no-repeat;
            background-size: contain;
        }
    }
    &.xls, &.xlsx{
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/excel.png') no-repeat;
            background-size: contain;
        }
    }
    &.img {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/img.png') no-repeat;
            background-size: contain;
        }
    }
    &.files {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/files.png') no-repeat;
            background-size: contain;
        }
    }
    &.pdf {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/pdf.png') no-repeat;
            background-size: contain;
        }
    }
    &.audio {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/audio.png') no-repeat;
            background-size: contain;
        }
    }
    &.video {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/video.png') no-repeat;
            background-size: contain;
        }
    }
    &.rest, &.unknown {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/rest.png') no-repeat;
            background-size: contain;
        }
    }
    &.comment {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/comment.png') no-repeat;
            background-size: contain;
        }
    }
    &.catalogue {
        &::before {
            display: none;
        }
    }
}

.manage-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: var(--srt-color-gray); 
    font-size: 14px;

    .state {
        // margin-right: 20px;
        .icon {
            color: #cccccc;
            font-size: 20px;
            display: inline-block;
            vertical-align: middle;
            margin-right: 6px;
        }

    }
    .time {
        font-size: 14px;
        &::before {
            content: '\e726';
            font-family: 'iconfont';
            display: inline-block;
            vertical-align: middle;
            transform: translateY(-1px);
            margin-right: 6px;
        }
        .blue {
            color: #47698C;
        }
    }
}

.manage-cate {
    padding-bottom: 20px;
}

.manage-op {
    display: flex;
    .op {
        display: flex;
        align-items: center;
    }
    .label {
        color: var(--srt-color-gray);
        margin-left: 8px;
        font-weight: 400;
    }
    .open-switch {
        :deep(.el-switch__core) {
            height: 22px;
            border-radius: 11px;
            .el-switch__action {
                width: 18px;
                height: 18px;
            }
        }
    }
    .open-switch.is-checked {
        :deep(.el-switch__core) {
            height: 22px;
            border-radius: 11px;
            .el-switch__action {
                width: 18px;
                height: 18px;
                left: calc(100% - 19px);
            }
        }
    }

}

.manage-tag {
    color: var(--srt-color-gray);
    font-size: 14px;
    margin-right: 20px;
    line-height: 28px;
    font-weight: 400;
    cursor: default;
    .iconfont {
        display: inline-block;
        vertical-align: middle;
        transform: translateY(-1px);
        margin-right: 6px;
        font-size: 16px;
        color: #91A5BA;
    }
    .show {
        color: #00b042;
    }
}


.manage-btn {
    text-align: right;
    padding: 20px 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .name {
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        font-size: 16px;
        color: var(--srt-main-text-color);
        max-width: 776px;

        :deep(.content-1){
            &::before {
                content: '';
                width: 4px;
                height: 15px;
                background: var(--srt-main-active-text-color);
                display: inline-block;
                vertical-align: middle;
                transform: translateY(-1px);
                margin-right: 8px;
            }
        }
    }

    .btn {
        padding-left: 14px;
        padding-right: 14px;
    }
}
.add-course-btns {
    margin-top: 13px;
    text-align: center;
    .new-add {
        margin-right: 20px;
    }
}
.no-data-info {
    font-size: 14px;
    color: var(--srt-color-gray);
    line-height: 22px;
    .btn {
        font-size: 14px;
        height: 22px;
    }
}
</style>